﻿using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using Box2DX.Dynamics;

namespace Expression.Samples.Physics.Behaviors {

	public class MouseDragJoint : Behavior<FrameworkElement> {

		private bool isMouseCaptured = false;
		private Point mouseDownPt;

		private Entity entity;
		private MouseJoint joint;

		protected override void OnAttached() {
			base.OnAttached();

		
			this.AssociatedObject.MouseLeftButtonDown += this.HandleMouseDown;
			this.AssociatedObject.MouseLeftButtonUp += this.HandleMouseUp;
			this.AssociatedObject.MouseMove += this.HandleMouseMove;
			this.AssociatedObject.LostMouseCapture += this.HandleLostCapture;
		}

		protected override void OnDetaching() {
			base.OnDetaching();
		}

		private void HandleMouseDown(object sender, MouseButtonEventArgs e) {
			this.entity = Entity.GetElementEntity(this.AssociatedObject);

			if (this.entity != null && this.AssociatedObject.CaptureMouse()) {

				MouseJointDef mouseJointDef = new MouseJointDef();
				mouseJointDef.Body1 = this.entity.Simulator.World.GetGroundBody();
				mouseJointDef.Body2 = this.entity.Body;
				mouseJointDef.MaxForce = 3000;
				mouseJointDef.TimeStep = 1.0f / 30;
				mouseJointDef.Target = this.entity.Simulator.SimulatorContext.ScreenToWorld(e.GetPosition(this.entity.Simulator.PhysicsContext.Host));

				this.joint = (MouseJoint)this.entity.Simulator.World.CreateJoint(mouseJointDef);



				this.isMouseCaptured = true;

				this.mouseDownPt = e.GetPosition(this.AssociatedObject);

				//this.entity.Body.PutToSleep();
			}
		}

		private void HandleMouseMove(object sender, MouseEventArgs e) {
			if (this.isMouseCaptured) {


				Point pt = e.GetPosition(this.entity.Simulator.PhysicsContext.Host);

				this.joint.SetTarget(this.entity.Simulator.SimulatorContext.ScreenToWorld(pt));
			}
		}

		private void HandleMouseUp(object sender, MouseEventArgs e) {
			this.AssociatedObject.ReleaseMouseCapture();
		}

		private void HandleLostCapture(object sender, MouseEventArgs e) {

			if (this.isMouseCaptured && this.joint != null) {
				this.isMouseCaptured = false;



				this.entity.Simulator.World.DestroyJoint(this.joint);

				this.joint = null;

				//this.entity.Body.PutToSleep();

				//this.entity.Body.WakeUp();
			}
		}


	}
}
